import 'dart:io';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_hx/services/user_service.dart';
import 'package:package_info_plus/package_info_plus.dart';

class HeaderIntercept extends Interceptor {
  PackageInfo? info;
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async{
    var token=UserService.to.token;
    if(token.isNotEmpty){
      options.headers["token"]=token;
    }
    info ??= await PackageInfo.fromPlatform();
    final time=DateTime.now().microsecondsSinceEpoch;
    final platform=Platform.isAndroid?"android":"ios";
    var sing="timestamp=$time&platform=$platform";
    if(token.isNotEmpty){
      sing+="&token=$token";
    }
    options.headers["timestamp"]=time;
    options.headers["platform"]=platform;
    options.headers["client_version"]=info?.version??"";
    options.headers["sign"]=md5.convert(utf8.encode(sing)).toString().toLowerCase();
    debugPrint("${options.uri}");
    return super.onRequest(options,handler);
  }
}